import React from "react";
import { Form, Input, Button, message } from 'antd'
import ForgetPassword from './forgetPassword'
import PropTypes from 'prop-types';
import { login } from '@/api/login/index'
import { loginLog } from '@/api/log/index'
import { useDispatch } from 'react-redux'
import { actions } from '@/core/store'
import { useNavigate } from 'react-router-dom'



const Index = (props) => {

  const { goRegister } = props
  const [form] = Form.useForm();
  const Dispatch = useDispatch()
  const navigate = useNavigate()

  const useLogin = async () => {
    try {
      const values = await form.validateFields();
      const res = await login({
        account: values.account,
        password: values.password,
      });
      if (res.status === 0) {
        await loginLog(res.results.account, res.results.name, res.results.email)
        Dispatch(actions.userRedux.setToken(res.token))
        Dispatch(actions.userInfo.setUserInfo(res.results))
        message.success('登录成功');
        navigate('/')
      }
    } catch (error) {
      console.log(error);
    }
  }
  return (
    <Form
      name="basic"
      form={form}
      labelCol={{ span: 5 }}
      wrapperCol={{ span: 17 }}
      style={{ maxWidth: 600 }}
    >
      <Form.Item
        label="账号"
        name="account"
        rules={[{ required: true, message: '请输入账号' },]}
      >
        <Input placeholder="请输入账号" />
      </Form.Item>
      <Form.Item
        label="密码"
        name="password"
        rules={[{ required: true, message: '请输入密码' },]}
      >
        <Input.Password placeholder="请输入密码" />
      </Form.Item>
      <Form.Item
        wrapperCol={{ span: 24 }}
      >
        <div className="login-btn-wrapper">
          <ForgetPassword>
            <div className="forget-password">忘记密码</div>
          </ForgetPassword>
          <div>
            <Button className="login-btn" type="primary" onClick={useLogin}>
              登录
            </Button>
          </div>
          <div className="register">还没有账号？<span className="register-go-btn" onClick={goRegister}>马上注册</span></div>
        </div>
      </Form.Item>
    </Form>
  )
}

Index.propTypes = {
  goRegister: PropTypes.func.isRequired,
};


export default Index
